package com.zlyx.easy.core.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zlyx.easy.core.map.EasyMap;
import com.zlyx.easy.core.utils.JsonUtils;
import com.zlyx.easy.core.utils.ObjectUtils;

/**
 * @Auth 赵光
 * @Desc 描述 JSON操作工具
 * @Date 2019年4月8日
 */
public class JsonUtils extends JSONObject {

	private static final long serialVersionUID = 1L;

	public JsonUtils() {
		super();
	}

	public JsonUtils(String key, Object value) {
		super(EasyMap.newMap(key, value));
	}

	public JsonUtils(Map<String, Object> map) {
		super(map);
	}

	public JsonUtils(boolean ordered) {
		super(ordered);
	}

	public JsonUtils(int initialCapacity) {
		super(initialCapacity);
	}

	public JsonUtils(int initialCapacity, boolean ordered) {
		super(initialCapacity, ordered);
	}

	public JsonUtils add(String key, Object value) {
		put(key, value);
		return this;
	}

	public <T> T getValue(String key) {
		return getValue(key, null);
	}

	@SuppressWarnings("unchecked")
	public <T> T getValue(String key, T defaultValue) {
		return containsKey(key) ? (T) get(key) : defaultValue;
	}

	@Override
	public List<Object> values() {
		return new ArrayList<>(values());
	}

	public static JsonUtils create() {
		return new JsonUtils();
	}

	public static JsonUtils create(String text) {
		return new JsonUtils(parse(text));
	}

	public static JsonUtils create(String key, Object value) {
		return new JsonUtils(key, value);
	}

	public static JsonUtils create(Map<String, Object> map) {
		return new JsonUtils(map);
	}

	public static JSONObject parse(String text) {
		if (ObjectUtils.isNotEmpty(text)) {
			return JSON.parseObject(text);
		}
		return null;
	}

	public static <T> T parseObject(Object o, Type type) {
		if (o != null) {
			return JSONObject.parseObject(JSON.toJSONString(o), type);
		}
		return null;
	}

	public static <T> T getProperty(JSONObject o, String name, Class<T> type) {
		if (o.containsKey(name)) {
			return JSON.parseObject(o.getString(name), type);
		}
		return null;
	}

}
